package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**聊天服务端
 * */
public class Server {
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private ServerSocket serverSocket;
/**
 * */
    public Server() {
        /**初始化服务端
         * */

        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8959);
            System.out.println("启动一个服务端完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        /**启动服务端
         * */

        try {
            while (true){
                System.out.println("等待客服端连接");
                Socket accept = serverSocket.accept();
                System.out.println("客服端连接成功！");

                InputStream is = accept.getInputStream();//低级流
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);//转换流
            BufferedReader br = new BufferedReader(isr);

            /**通过br.readLine()读取客服端的字符串
             * 当客户端调用socket.close()
             * */
            String message;
            while ((message= br.readLine())!=null){
                System.out.println(message);
            }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }



//        try {
//            System.out.println("等待客服端连接");
//            Socket accept = serverSocket.accept();
//            System.out.println("客服端连接成功！");
//            InputStream is = accept.getInputStream();//低级流
//            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);//转换流
//            BufferedReader br = new BufferedReader(isr);
//
//            /**通过br.readLine()读取客服端的字符串
//             * 当客户端调用socket.close()
//             * */
//            String message;
//            while ((message= br.readLine())!=null){
//                System.out.println(message);
//            }
//
//
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }


    }
}
